package com.scpii.universal.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.AppApiDto;
import com.scpii.universal.dto.AppApiResultDto;
import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.exception.GenericException;
import com.scpii.universal.hibernate.dao.AppDao;
import com.scpii.universal.hibernate.dao.AppIconDao;
import com.scpii.universal.hibernate.dao.AppPartnerDao;
import com.scpii.universal.hibernate.dao.AppUpdateDao;
import com.scpii.universal.hibernate.dao.AttributeDao;
import com.scpii.universal.hibernate.dao.CatelogDao;
import com.scpii.universal.hibernate.dao.EnterpriseDao;
import com.scpii.universal.hibernate.dao.ManageUserDao;
import com.scpii.universal.hibernate.dao.PartnerDao;
import com.scpii.universal.hibernate.dao.SysCateAttributeDao;
import com.scpii.universal.hibernate.dao.SystemCateDao;
import com.scpii.universal.hibernate.entity.AppIconTab;
import com.scpii.universal.hibernate.entity.AppPartnerTab;
import com.scpii.universal.hibernate.entity.AppTab;
import com.scpii.universal.hibernate.entity.AppUpdateTab;
import com.scpii.universal.hibernate.entity.AttributeTab;
import com.scpii.universal.hibernate.entity.CatelogTab;
import com.scpii.universal.hibernate.entity.EnterpriseTab;
import com.scpii.universal.hibernate.entity.ManageUserTab;
import com.scpii.universal.hibernate.entity.PartnerTab;
import com.scpii.universal.hibernate.entity.SysCateAttributeTab;
import com.scpii.universal.hibernate.entity.SystemCateTab;
import com.scpii.universal.service.CatelogInterface;
import com.scpii.universal.service.CreateAppService;
import com.scpii.universal.service.ManageUserService;
import com.scpii.universal.util.CacheUtil;
import com.scpii.universal.util.EhCacheManager;
import com.scpii.universal.util.ImgAndFilePath;
import com.scpii.universal.util.UtilTool;

@Service
public class CeateAppServiceImpl extends BaseServiceImpl<PartnerTab, Integer> implements CreateAppService {
	@Resource
	private PartnerDao partnerDao;
	@Resource
	private EnterpriseDao enterpriseDao;
	@Resource
	private ManageUserDao manageUserDao;
	@Resource
	private ManageUserService manageUserService;
	@Resource
	private AppDao appDao;
	@Resource
	private SystemCateDao systemCateDao;
	@Resource
	private CatelogDao catelogDao;
	@Resource
	private SysCateAttributeDao sysCateAttributeDao;
	@Resource
	private AttributeDao attributeDao;
	@Resource
	private AppUpdateDao appUpdateDao;
	@Resource
	private AppPartnerDao appPartnerDao;
	@Resource
	private AppIconDao appIconDao;
	@Resource
	private CatelogInterface catelogInterface;

	@Resource
	public void setBaseDao(PartnerDao partnerDao) {
		super.setBaseDao(partnerDao);
	}

	protected ResourceBundle bundle = ResourceBundle.getBundle(GenericConstants.GLOBAL_PROPERTIES_PATH,
			Locale.getDefault());
	private Log log = LogFactory.getLog(this.getClass());

	@Override
	public AppApiResultDto saveCeateApp(AppApiDto appApiDto, String webAppsRealPath) {

		try {
			// 保存企业信息
			String nowDate = new SimpleDateFormat(GenericConstants.DATE_FORMAT).format(new Date());
			EnterpriseTab enterTab = appApiDto.getEnterInfo();
			enterTab.setDatUpdateDatetime(nowDate);
			enterTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			enterTab.setIntEnterpTradeType(86);//咨询服务
			enterpriseDao.save(enterTab);
			// 生成平台账号生成 ManageUserTab varRoleType=0：生成平台账号；varRoleType=1：后台管理平台
			Integer enterId = enterTab.getIntEnterpId();
			String dateString = UtilTool.dateToString(new Date());
			String paireKey = dateString.replaceAll("-", "").replaceAll(":", "").replaceAll(" ", "");
			ManageUserTab userTab = new ManageUserTab();
			userTab.setIntEnterpId(enterId);
			userTab.setVarRoleType(0);
			String userName = generateIconName();
			userTab.setVarLoginName(userName);
			userTab.setVarPassword(CacheUtil.generatePassword(userName));
			userTab.setVarPaireKey(paireKey);
			userTab.setDatUpdateDatetime(nowDate);
			userTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			manageUserDao.save(userTab);

			// 内容平台用户生成
			ManageUserTab contetnUser = new ManageUserTab();
			contetnUser.setIntEnterpId(enterId);
			contetnUser.setVarRoleType(1);
			String contentUser = generateIconName();
			contetnUser.setVarLoginName(contentUser);
			contetnUser.setVarPassword(CacheUtil.generatePassword(userName));
			contetnUser.setVarPaireKey(paireKey);
			contetnUser.setDatUpdateDatetime(nowDate);
			contetnUser.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			manageUserDao.save(contetnUser);

			// 封装数据
			AppTab appTab = new AppTab();
			appTab.setVarAppName(appApiDto.getAppName());
			// 保存应用
			UserInfoDto user = new UserInfoDto();
			user.setIntEnterpId(enterId);
			user.setIntUserId(userTab.getIntUserId());

			Integer appId = this.save(appTab, user);
			// 将app信息 与企业信息关联

			AppPartnerTab appab = new AppPartnerTab();
			appab.setIntAppId(appId);
			appab.setIntPartnerId(appApiDto.getPtId());
			appab.setIntEnterpId(enterId);
			appab.setVarInterfaceUrl(appApiDto.getInterfaceUrl());
			appab.setDatUpdateDatetime(nowDate);
			appab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			appPartnerDao.save(appab);
			
			//保存icon
			Integer iconId = this.saveAppIcon(appId, null);
			//创建LOADING图片的记录，此时没有URL
			Integer loadingIconId = this.saveAppLoadingIcon(new AppIconTab(), appId);

			// 创建安卓和IOS的应用版本更新记录
			AppUpdateTab updAndroid = saveAppVersionUpdate(appId, GenericConstants.OPERATION_SYS_ANDROID, iconId,
					loadingIconId);
			AppUpdateTab updIOS = saveAppVersionUpdate(appId, GenericConstants.OPERATION_SYS_IOS, iconId, loadingIconId);
			user.setAndroidVersionUpdate(updAndroid);
			user.setIosVersionUpdate(updIOS);
			// 创建图片资源目录
			ImgAndFilePath.createWorkPic(webAppsRealPath, user.getIntEnterpId(), appId);

			// 复制系统分类及属性到分类、属性表里
			copySysCatelog(user.getIntEnterpId(), appId);
			
			//调用分类内容接口
			int interfaceResult = catelogInterface.save(appab);
			/*if (interfaceResult == 2)
				throw new GenericException("接口地址不可用,无法同步数据！");*/
			
			// 返回信息
			AppApiResultDto resultDto = new AppApiResultDto();
			resultDto.setAppId(appId);
			resultDto.setAppAccount(userName);
			resultDto.setContentAccount(contentUser);
			resultDto.setPassword(userName);
			resultDto.setStatus(1);
			resultDto.setResultmsg("合作商ID为："+appApiDto.getPtId()+" 生成成功");
			resultDto.setAppmanagerUrl(getServerUrl()+"universalWeb");
			return resultDto;
		} catch (Exception e) {
			throw new GenericException("合作商ID为" + appApiDto.getPtId()
					+ " 生成失败," + e.getMessage());
		}

	}

	@Override
	public String getKeyById(Integer id) {
		PartnerTab tab = partnerDao.get(id);
		if (tab != null && tab.getIntDeleteSign() == GenericConstants.DELETE_SIGN_EXIST) {
			return tab.getVarSecretKey();
		} else {
			return null;
		}
	}

	/**
	 * 保存应用 更新用户表
	 * 
	 * @param appTab
	 * @param userInfo
	 * @return
	 * @author zhangqiang 2012-10-11下午03:02:31
	 */

	private Integer save(AppTab appTab, UserInfoDto userInfo) {
		appTab.setIntEnterpId(userInfo.getIntEnterpId());// 企业ID
		appTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);// 逻辑删除符
		appTab.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));// 更新时间
		appTab.setIntNavigatestyleId(0);// 导航风格，默认0
		appTab.setIntAppStyleId(0);//应用风格
		Integer appId = appDao.save(appTab);
		// 更新用户应用ID
		String varPaireKey = manageUserDao.getUserInfoById(userInfo.getIntUserId(),
				new String[] { "varPaireKey" }).getVarPaireKey();
		StringBuffer hql = new StringBuffer("update ManageUserTab m set");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		hql.append(" m.intAppId=:intAppId");
		argsMap.put("intAppId", appId);
		hql.append(" where m.intDeleteSign=:intDeleteSign");
		hql.append(" and m.varPaireKey=:varPaireKey");
		argsMap.put("intDeleteSign", GenericConstants.DELETE_SIGN_EXIST);
		argsMap.put("varPaireKey", varPaireKey);
		manageUserDao.hqlOperation(hql.toString(), argsMap);
		return appId;
	}

	/**
	 * 保存版本更新记录
	 * 
	 * @param appId
	 * @param type
	 * @param iconId
	 * @param loadingIconId
	 * @return
	 * @author liuhj 2012-7-18下午05:55:09
	 */
	private AppUpdateTab saveAppVersionUpdate(int appId, int type, int iconId, int loadingIconId) {
		AppUpdateTab appUpd = new AppUpdateTab();
		appUpd.setIntAppId(appId);
		appUpd.setIntAppOsType(type);// 操作系统类型
		appUpd.setIntIconId(iconId);// 应用ICON
		appUpd.setIntLoadingIconId(loadingIconId);// LOADING ICON
		appUpd.setDobAppVersion(GenericConstants.APP_UPDATE_FIRST_VERSION);// VERSION
		appUpd.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		appUpd.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		appUpd.setVarAppSign("universal" + appId);
		appUpd.setIntAppBackgImgId(0);
		appUpd.setIntAppNavigateBgImgId(0);
		appUpd.setIntAppTitleBgImgId(0);
		appUpd.setIntNavBgImgId(0);
		appUpd.setIntState(GenericConstants.APP_VERSION_UPDATE_NO);
		appUpd.setIntIsDeploy(GenericConstants.APP_VERSION_DEPLOYED_NO);
		appUpdateDao.save(appUpd);

		log.info("创建应用版本更新记录" + type);
		return appUpd;
	}

	/**
	 * 复制系统分类到分类表
	 * 
	 * @param intEnterpId
	 * @param appId
	 * @author liuhj 2012-7-20下午01:43:31
	 */
	private void copySysCatelog(int intEnterpId, int appId) {
		List<SystemCateTab> lstSysCate = systemCateDao.getAll();
		if (lstSysCate == null || lstSysCate.size() <= 0) {
			return;
		}
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		for (SystemCateTab systemCateTab : lstSysCate) {
			int catelogType = getCatelogType(systemCateTab.getVarSysCateName().trim());
			if (catelogType == 3) {
				if ("false".equals(EhCacheManager
						.getObject(GenericConstants.COPY_HOUSE_SYSCATELOG)))
					continue;//不复制房产聚合
			}
			CatelogTab catelog = new CatelogTab();
			catelog.setDatUpdateDatetime(date);
			catelog.setIntAppId(appId);
			catelog.setIntEnterpId(intEnterpId);
			catelog.setVarCateName(systemCateTab.getVarSysCateName());
			catelog.setIntParentCateId(0);
			catelog.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			catelog.setIntHasSubCate(0);
			catelog.setIntType(getCatelogType(systemCateTab.getVarSysCateName().trim()));
			int catelogId = catelogDao.save(catelog);
			List<SysCateAttributeTab> lstAttribute = sysCateAttributeDao.getAttributeByCateId(systemCateTab
					.getIntSysCateId());
			log.info("复制系统分类到分类表---> ID：" + systemCateTab.getIntSysCateId() + " 分类名称："
					+ systemCateTab.getVarSysCateName() + " 父ID：" + systemCateTab.getIntParentSysCateId());
			if (lstAttribute != null && lstAttribute.size() > 0) {
				// 复制属性
				this.copySysCatelogAttribute(lstAttribute, catelogId);
			}
		}
	}

	/**
	 * 复制系统属性到属性表
	 * 
	 * @param lstAttribute
	 * @param catelogId
	 * @author liuhj 2012-7-20下午02:33:47
	 */
	private void copySysCatelogAttribute(List<SysCateAttributeTab> lstAttribute, int catelogId) {
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		for (SysCateAttributeTab sysCateAttributeTab : lstAttribute) {
			AttributeTab attribute = new AttributeTab();
			attribute.setIntCateId(catelogId);
			attribute.setVarAttriName(sysCateAttributeTab.getVarAttributeName());
			attribute.setDatUpdateDatetime(date);
			attribute.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			attribute.setIntType(getAttrType(sysCateAttributeTab.getVarAttributeName().trim()));
			attribute.setIntInputType(getAttrInputType(sysCateAttributeTab.getVarAttributeName().trim()));
			attributeDao.save(attribute);
			log.info("复制系统分类属性到属性表---> 属性名称：" + sysCateAttributeTab.getVarAttributeName());
		}
	}

	/**
	 * 获取分类类型
	 * 
	 * @author Taylor 2012-9-19 上午09:34:44
	 * @param parentCateName
	 * @return int
	 */
	private int getCatelogType(String parentCateName) {
		if (bundle.getString("sysCatelog.product").equals(parentCateName))
			return 0;
		if (bundle.getString("sysCatelog.news").equals(parentCateName))
			return 1;
		if (bundle.getString("sysCatelog.activity").equals(parentCateName))
			return 2;
		if (bundle.getString("sysCatelog.house").equals(parentCateName))
			return 3;
		return 0;
	}

	/**
	 * 系统属性类型
	 * 
	 * @author Taylor 2012-9-17 下午04:31:17
	 * @param parentAttrName
	 * @return int
	 */
	private int getAttrType(String parentAttrName) {
		if (bundle.getString("sysAttribute.phone_num").equals(parentAttrName))
			return 8;
		if (bundle.getString("sysAttribute.area").equals(parentAttrName))
			return 9;
		if (bundle.getString("sysAttribute.price").equals(parentAttrName))
			return 10;
		if (bundle.getString("sysAttribute.house_type").equals(parentAttrName)) // 户型
			return 11;
		return 0;
	}

	/**
	 * 系统属性输入类型
	 * 
	 * @author Taylor 2012-9-17 下午04:31:17
	 * @param parentAttrName
	 * @return int
	 */
	private int getAttrInputType(String parentAttrName) {
		if (bundle.getString("sysAttribute.area").equals(parentAttrName))
			return GenericConstants.ATTRIBUTE_INPUT_TYPE_SELECT;
		return GenericConstants.ATTRIBUTE_INPUT_TYPE_INPUT;
	}

	/**
	 * 生成唯一的用户名
	 * 
	 * @return
	 * @author liuhj 2012-7-12下午05:47:56
	 */
	private String generateIconName() {
		char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
				'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6',
				'7', '8', '9' };
		Random random = new Random();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < 6; i++) {
			buf.append(codeSequence[random.nextInt(36)]);
		}

		// 检测用户名的唯一性
		String userName = buf.toString();
		List<ManageUserTab> list = manageUserService.checkUserName(userName);
		// 账号存在
		if (list != null && list.size() > 0) {
			this.generateIconName();
		}
		return userName;
	}
	
	/**
	 * 创建LOADING的图标记录
	 * @param appIconTab
	 * @param appId
	 * @return
	 * @author liuhj
	 * 2012-7-19下午02:43:59
	 */
	private Integer saveAppLoadingIcon(AppIconTab appIconTab, int appId) {
		//保存LOADING
		appIconTab.setIntAppId(appId);
		if (appIconTab.getIntIconName() == null) {
			appIconTab.setIntIconName(GenericConstants.LOADING_DEFAULT_NAME);
		}
		appIconTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		appIconTab.setIntIconType(GenericConstants.ICON_TYPE_LOADING);
		appIconTab.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
			.format(new Date()));
		appIconTab.setIntIconDefineType(GenericConstants.ICON_DEFINE_TYPE_USER);
		Integer loadingIconId = appIconDao.save(appIconTab);
		log.info("为应用创建LOADING图片记录");
		return loadingIconId;
	}
	
	/**
	 * 保存应用图标
	 * @param appId
	 * @param iconURL
	 * @return
	 * @author liuhj
	 * 2012-7-18下午05:56:45
	 */
	private Integer saveAppIcon(int appId, String iconURL) {
		AppIconTab appIconTab = new AppIconTab();
		appIconTab.setIntAppId(appId);
		appIconTab.setIntIconName(GenericConstants.APP_ICON_DEFAULT_NAME);
		appIconTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		appIconTab.setIntIconType(GenericConstants.ICON_TYPE_APP_ICON);
		appIconTab.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
			.format(new Date()));
		appIconTab.setIntIconDefineType(GenericConstants.ICON_DEFINE_TYPE_USER);
		appIconTab.setVarIconUrl(iconURL);
		Integer iconId = appIconDao.save(appIconTab);
		return iconId;
	}

}
